//
//  XHBrokenLine.m
//  DrawTool
//
//  Created by sos on 16/3/9.
//  Copyright © 2016年 li_yong. All rights reserved.
//

#import "XHBrokenLine.h"
#import <UIKit/UIKit.h>

#define ANIMATION_DURING 2
#define LINE_WIDTH  1

#define BAR_WIDTH 30
#define ANIMATION_DURINGo 0.5

#define Angle(percent) 2*M_PI*percent
#define PIE_RADIUS (self.frame.size.height>self.frame.size.width?self.frame.size.width:self.frame.size.height)/4

#define MARGIN_BETWEEN_X_POINT 375/6  //X轴的坐标点的间距
#define MAX_POINT_WITHIN_SCREEN 6   //一屏幕最多容纳的坐标数

@interface XHBrokenLine()

//数据源
@property (strong, nonatomic) NSMutableArray *dataSource;

@end


@implementation XHBrokenLine

- (id)initWithFrame:(CGRect)frame
     withDataSource:(NSMutableArray *)dataSource
           withType:(ChartViewType)type
      withAnimation:(BOOL)isAnimation
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.autoresizesSubviews = NO;
        self.dataSource = [NSMutableArray arrayWithArray:dataSource];
        self.chartViewType = type;
        self.isAnimation = isAnimation;
//        [self buildView];
    }
    return self;
}
+(UIView *)drawTool:(UIView *)view dataArr:(NSArray *)dataArr chartViewType:(ChartViewType)type color:(UIColor *)color
{
    NSMutableArray *dataSource = [NSMutableArray arrayWithCapacity:0];
    for (NSInteger i = 0; i < dataArr.count; i++) {
        
        CoordinateItem *item = [[CoordinateItem alloc] initWithXValue:[NSString stringWithFormat:@"%ld",i]
                                                           withYValue:dataArr[i]
                                                            withColor:color];
        [dataSource addObject:item];

    }
    XHBrokenLine *sos = [[XHBrokenLine alloc]init];
//    [sos buildView:view chartViewType:LineChartViewType data:dataSource];
    [sos buildView:view chartViewType:LineChartViewType data:dataSource color:color];
    
    
    return view;
}
- (void)buildView:(UIView *)view chartViewType:(ChartViewType)type data:(NSMutableArray *)data color:(UIColor *)color
{
    self.backgroundColor = [UIColor whiteColor];
    
    switch (self.chartViewType)
    {
        case LineChartViewType:
        {
            //根据数据源设置图形的尺寸
//            [self sizeForDataSource:view];
            
            //折线图
            LineChartView *lineChartView = [[LineChartView alloc] initWithDataSource:data
                                                               withLineAndPointColor:color
                                                                       withAnimation:self.isAnimation];
            lineChartView.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
            [view addSubview:lineChartView];

        }
            break;
        case BarChartViewType:
        {
            //柱状图的数据源需要特殊处理(数据源的开始位置和结束位置需要添加空数据，方便绘制柱状体)
            CoordinateItem *firstItem = [[CoordinateItem alloc] initWithXValue:@""
                                                                    withYValue:@""
                                                                     withColor:[UIColor purpleColor]];
            [data insertObject:firstItem atIndex:0];
            CoordinateItem *lastObject = [[CoordinateItem alloc] initWithXValue:@""
                                                                     withYValue:@""
                                                                      withColor:[UIColor purpleColor]];
            [data insertObject:lastObject atIndex:[data count]];
            
            //根据数据源设置图形的尺寸
//            [self sizeForDataSource];
            
            //柱状图
            BarChartView *barChartView = [[BarChartView alloc] initWithDataSource:data
                                                                        withColor:[UIColor blueColor]
                                                                    withAnimation:self.isAnimation];
            barChartView.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
            [view addSubview:barChartView];
        }
            break;
        case PieChartViewType:
        {
            //饼状图
            PieChartView *pieChartView = [[PieChartView alloc] initWithDataSource:data withAimation:self.isAnimation];
            pieChartView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
            pieChartView.pieRadius = 35;
            [view addSubview:pieChartView];
        }
            break;
        default:
            break;
    }
}
//- (void)sizeForDataSource:(UIView *)view
//{
    //根据数据源的个数设置DrawView的内容Size
//    NSUInteger valueCount = [self.dataSource count];
//    if (valueCount > MAX_POINT_WITHIN_SCREEN)
//    {
//        self.contentSize = CGSizeMake(self.frame.size.width + (valueCount - MAX_POINT_WITHIN_SCREEN) * MARGIN_BETWEEN_X_POINT, self.frame.size.height);
//    }else
//    {
//        self.contentSize = CGSizeMake(self.frame.size.width - (MAX_POINT_WITHIN_SCREEN - valueCount) * MARGIN_BETWEEN_X_POINT, self.frame.size.height);
//    }
//    [self addSubview:view];
//}
/**
 *  @author li_yong
 *
 *  根据数据源设置图形的尺寸
 */
//- (void)sizeForDataSource
//{
//    //根据数据源的个数设置DrawView的内容Size
//    NSUInteger valueCount = [self.dataSource count];
//    if (valueCount > MAX_POINT_WITHIN_SCREEN)
//    {
//        self.contentSize = CGSizeMake(self.frame.size.width + (valueCount - MAX_POINT_WITHIN_SCREEN) * MARGIN_BETWEEN_X_POINT, self.frame.size.height);
//    }else
//    {
//        self.contentSize = CGSizeMake(self.frame.size.width - (MAX_POINT_WITHIN_SCREEN - valueCount) * MARGIN_BETWEEN_X_POINT, self.frame.size.height);
//    }
//}
//

@end


#pragma CoordinateItem

@implementation CoordinateItem

/**
 *  @author li_yong
 *
 *  构造函数
 *
 *  @param xValue X坐标值
 *  @param yValue Y坐标值
 *
 *  @return
 */
- (id)initWithXValue:(NSString *)xValue withYValue:(NSString *)yValue
{
    self = [super init];
    if (self)
    {
        self.coordinateXValue = xValue;
        self.coordinateYValue = yValue;
    }
    return self;
}

/**
 *  @author li_yong
 *
 *  构造函数
 *
 *  @param xValue    X坐标值
 *  @param yValue    Y坐标值
 *  @param itemColor item的颜色
 *
 *  @return
 */
- (id)initWithXValue:(NSString *)xValue
          withYValue:(NSString *)yValue
           withColor:(UIColor *)itemColor
{
    self = [super init];
    if (self)
    {
        self.coordinateXValue = xValue;
        self.coordinateYValue = yValue;
        self.itemColor = itemColor;
    }
    return self;
}

@end

#pragma BaseChartView

@interface BaseChartView()

@end

@implementation BaseChartView

/**
 *  @author li_yong
 *
 *  构造函数
 *
 *  @param dataSource 数据源
 *
 *  @return
 */
- (id)initWithDataSource:(NSMutableArray *)dataSource
{
    self = [super init];
    if (self)
    {
        self.dataSource = dataSource;
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    //绘制坐标系
    [self drawCoordinate];
}

- (void)drawCoordinate
{
    CGContextRef currentCtx = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(currentCtx, [[UIColor whiteColor] CGColor]);
    CGContextSetLineWidth(currentCtx, 0.5);
    
    //1.绘制X轴和y轴
//    //第一种方法绘制四条线
//    CGPoint poins[] = {CGPointMake(MARGIN_LEFT, MARGIN_TOP),
//        CGPointMake(self.frame.size.width - MARGIN_LEFT, MARGIN_TOP),
//        CGPointMake(self.frame.size.width - MARGIN_LEFT, self.frame.size.height - MARGIN_TOP),
//        CGPointMake(MARGIN_LEFT, self.frame.size.height - MARGIN_TOP)};
//    CGContextAddLines(currentCtx,poins,4);
//    CGContextClosePath(currentCtx);
//    CGContextStrokePath(currentCtx);
    
    /*
     //第二种方法绘制一个矩形
     CGContextMoveToPoint(currentCtx, MARGIN_LEFT, MARGIN_TOP);
     CGContextSetLineWidth(currentCtx, 0.1);
     CGContextSetRGBStrokeColor(currentCtx, 0.5, 0.5, 0.5, 1);
     CGContextAddRect(currentCtx, CGRectMake(MARGIN_LEFT, MARGIN_TOP, self.frame.size.width - 2*MARGIN_LEFT, self.frame.size.height - 2*MARGIN_TOP));
     CGContextClosePath(currentCtx);
     CGContextStrokePath(currentCtx);
     */
    
    //2.绘制虚线(暂时设置纵坐标分5个区间)
    //虚线间距
    self.dashedSpace = (CGFloat)(self.frame.size.height - 2*MARGIN_TOP)/Y_SECTION;
    //设置虚线属性
//    CGFloat lengths[2] = {5,5};
//    CGContextSetLineDash(currentCtx, 0, lengths, 1);
//    for(int index = 1; index<Y_SECTION; index++)
//    {
//        CGContextMoveToPoint(currentCtx, MARGIN_LEFT, MARGIN_TOP + self.dashedSpace * index);
//        CGContextAddLineToPoint(currentCtx, self.frame.size.width - MARGIN_LEFT, MARGIN_TOP + self.dashedSpace * index);
//    }
//    CGContextStrokePath(currentCtx);
    
    //3.设置纵坐标值
    self.maxYValue = [self compareForMaxValue];
    self.yNumberSpace = self.maxYValue/Y_SECTION;
    for (int index = 0; index<Y_SECTION+1; index++)
    {
        CGPoint centerPoint = CGPointMake(MARGIN_LEFT/2, MARGIN_TOP + self.dashedSpace * index);
        CGRect bounds = CGRectMake(0, 0, MARGIN_LEFT - 10, 15);
        NSString *labelText = [NSString stringWithFormat:@"%d",self.yNumberSpace * (Y_SECTION - index)];
        UILabel *yNumber = [self createLabelWithCenter:centerPoint
                                            withBounds:bounds
                                              withText:labelText
                                     withtextAlignment:NSTextAlignmentRight];
        [self addSubview:yNumber];
    }
    
    //4.设置横坐标值
    for (int index = 0; index<[self.dataSource count]; index++)
    {
        CGPoint centerPoint = CGPointMake(MARGIN_LEFT + MARGIN_BETWEEN_X_POINT * index, self.frame.size.height - MARGIN_TOP/2 - 4);
        CGRect bounds = CGRectMake(0, 0, MARGIN_BETWEEN_X_POINT, 15);
        CoordinateItem *item = [self.dataSource objectAtIndex:index];
        UILabel *xNumber = [self createLabelWithCenter:centerPoint
                                            withBounds:bounds
                                              withText:item.coordinateXValue
                                     withtextAlignment:NSTextAlignmentCenter];
        [self addSubview:xNumber];
    }
}

/**
 *  @author li_yong
 *
 *  获取最大的纵坐标值
 */
- (int)compareForMaxValue
{
    __block int maxYValue = 0;
    //获取最大的纵坐标值
    [self.dataSource enumerateObjectsUsingBlock:^(CoordinateItem *obj, NSUInteger idx, BOOL *stop) {
        if ([obj.coordinateYValue intValue] > maxYValue)
        {
            maxYValue = [obj.coordinateYValue intValue];
        }
    }];
    //获取最大的纵坐标值整数
    if((maxYValue % Y_SECTION) != 0)
    {
        maxYValue = maxYValue + (Y_SECTION - maxYValue % Y_SECTION);
    }
    return maxYValue;
}

/**
 *  @author li_yong
 *
 *  UILabel的工厂方法
 *
 *  @param centerPoint   label的中心
 *  @param bounds        label的大小
 *  @param labelText     label的内容
 *  @param textAlignment label的内容排版方式
 *
 *  @return
 */
- (UILabel *)createLabelWithCenter:(CGPoint)centerPoint
                        withBounds:(CGRect)bounds
                          withText:(NSString *)labelText
                 withtextAlignment:(NSTextAlignment)textAlignment
{
//    UILabel *label = [[UILabel alloc] init];
//    label.center = centerPoint;
//    label.bounds = bounds;
//    label.textAlignment = NSTextAlignmentCenter;
//    label.backgroundColor = [UIColor clearColor];
//    label.font = [UIFont systemFontOfSize:10];
//    label.textAlignment = textAlignment;
//    label.text = labelText;
    UILabel *label = [[UILabel alloc]init];
    label.bounds = bounds;
    label.center = centerPoint;
//    label.layer.borderColor = [UIColor whiteColor].CGColor;
    label.textColor = [UIColor whiteColor];
    label.layer.borderWidth = 0;
//    label.backgroundColor = [UIColor redColor];
    
    return label;
}

@end

#pragma LineChartView

@interface LineChartView()

//折线和标点的颜色
@property (strong, nonatomic) UIColor *lineAndPointColor;

//是否动态绘制
@property (assign, nonatomic) BOOL isAnimation;

@end

@implementation LineChartView

/**
 *  @author li_yong
 *
 *  构建方法
 *
 *  @param dataSource  数据源
 *  @param color       折线点和折线的颜色
 *  @param isAnimation 是否动态绘制
 *
 *  @return
 */
- (id)initWithDataSource:(NSMutableArray *)dataSource
   withLineAndPointColor:(UIColor *)color
           withAnimation:(BOOL)isAnimation
{
    self = [super initWithDataSource:dataSource];
    if (self)
    {
        self.lineAndPointColor = color;
        self.isAnimation = isAnimation;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];
    
    CGContextRef currentCtx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(currentCtx, self.lineAndPointColor.CGColor);
    CGContextSetStrokeColorWithColor(currentCtx, self.lineAndPointColor.CGColor);
    CGContextSetLineWidth(currentCtx, 1);
    
    //绘制坐标点
    NSMutableArray *coordinateArray = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *initCoordinateArray = [NSMutableArray arrayWithCapacity:0];
    for (int index = 0; index<[self.dataSource count]; index++)
    {
        CoordinateItem *item = [self.dataSource objectAtIndex:index];
        /**
         *  self.dashedSpace/self.yNumberSpace:计算纵轴上点与点间距(1和2、2和3)
         */
        CGPoint itemCoordinate = CGPointMake(MARGIN_LEFT + index * MARGIN_BETWEEN_X_POINT,
                                             self.frame.size.height - (MARGIN_TOP + [item.coordinateYValue integerValue]*(self.dashedSpace/self.yNumberSpace)));
        //记录坐标点
        [coordinateArray addObject:NSStringFromCGPoint(itemCoordinate)];
        CGContextAddArc(currentCtx, itemCoordinate.x, itemCoordinate.y, 4, 0, 2*M_PI, 1);
        CGContextFillPath(currentCtx);
        //记录初始化坐标点，方便后续动画
        itemCoordinate.y = self.frame.size.height - MARGIN_TOP;
        [initCoordinateArray addObject:NSStringFromCGPoint(itemCoordinate)];
    }
    CGContextStrokePath(currentCtx);
    
    //绘制折线
    //避免折线虚线化
    CGContextSetLineDash(currentCtx, 0, 0, 0);
    //绘图路线
    CGMutablePathRef path = CGPathCreateMutable();
    for (int index = 0; index<[coordinateArray count]-1; index++)
    {
        //一段折线开始点
        NSString *startPointStr = [coordinateArray objectAtIndex:index];
        CGPoint startPoint = CGPointFromString(startPointStr);
        
        //一段折线结束点
        NSString *endPointStr = [coordinateArray objectAtIndex:index+1];
        CGPoint endPoint = CGPointFromString(endPointStr);
        
        //绘制图线方法一：每一段折线都是用一个path,动画过程就变成分动动画,而且是同时执行的。
        //        [self drawLineWithStartPoint:startPoint
        //                        withEndPoint:endPoint];
        
        //绘制图线方法二：所有的绘图信息放在同一个path中,动画过程就变成连续的了。
        [self drawLineWithPath:path
                withStartPoint:startPoint
                  withEndPoint:endPoint];
        
        /*  使用CoreGraphics直接绘制
         CGContextMoveToPoint(currentCtx, startPoint.x, startPoint.y);
         CGContextAddLineToPoint(currentCtx, endPoint.x, endPoint.y);
         */
    }
    CGContextStrokePath(currentCtx);
    CGPathRelease(path);
}

/**
 *  @author li_yong
 *
 *  绘制折线
 *
 *  @param startPoint     折线的开始点
 *  @param endPoint       折线的结束点
 */
- (void)drawLineWithStartPoint:(CGPoint)startPoint
                  withEndPoint:(CGPoint)endPoint
{
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    lineLayer.lineWidth = 1;
    lineLayer.lineCap = kCALineCapButt;
    lineLayer.strokeColor = self.lineAndPointColor.CGColor;
    lineLayer.fillColor = nil;
    
    CGMutablePathRef linePath = CGPathCreateMutable();
    CGPathMoveToPoint(linePath, nil, startPoint.x, startPoint.y);
    CGPathAddLineToPoint(linePath, nil, endPoint.x, endPoint.y);
    lineLayer.path = linePath;
    
    if (self.isAnimation)
    {
        CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        pathAnimation.duration = ANIMATION_DURING;
        pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
        pathAnimation.autoreverses = NO;
        pathAnimation.fillMode = kCAFillModeForwards;
        [lineLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    }
    
    //    self.clipsToBounds = YES;
    [self.layer addSublayer:lineLayer];
    CGPathRelease(linePath);
}

/**
 *  @author li_yong
 *
 *  绘制折线
 *
 *  @param path       保存绘图信息的路径
 *  @param startPoint 折线的开始点
 *  @param endPoint   折线的结束点
 */
- (void)drawLineWithPath:(CGMutablePathRef )path
          withStartPoint:(CGPoint)startPoint
            withEndPoint:(CGPoint)endPoint
{
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    lineLayer.lineWidth = LINE_WIDTH;
    lineLayer.lineCap = kCALineCapButt;
    lineLayer.strokeColor = self.lineAndPointColor.CGColor;
    lineLayer.fillColor = nil;
    
    CGPathMoveToPoint(path, nil, startPoint.x, startPoint.y);
    CGPathAddLineToPoint(path, nil, endPoint.x, endPoint.y);
    lineLayer.path = path;
    
    if (self.isAnimation)
    {
        CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        pathAnimation.duration = ANIMATION_DURING;
        pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
        pathAnimation.autoreverses = NO;
        pathAnimation.fillMode = kCAFillModeForwards;
        [lineLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    }
    
    //    self.clipsToBounds = YES;
    [self.layer addSublayer:lineLayer];
}

@end

#pragma BarChartView

@interface BarChartView()

//柱形的颜色
@property (strong, nonatomic) UIColor *barColor;

//是否动态绘制
@property (assign, nonatomic) BOOL isAnimation;

@end

@implementation BarChartView

- (id)initWithDataSource:(NSMutableArray *)dataSource
               withColor:(UIColor *)color
           withAnimation:(BOOL)isAnimation
{
    self = [super initWithDataSource:dataSource];
    if (self)
    {
        self.barColor = color;
        self.isAnimation = isAnimation;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];
    
    CGContextRef currentCtx = UIGraphicsGetCurrentContext();
    
    for(int index = 0; index<[self.dataSource count]; index++)
    {
        CoordinateItem *item = [self.dataSource objectAtIndex:index];
        if(([item.coordinateXValue length] == 0)||
           ([item.coordinateYValue length] == 0))
        {
            //空数据就不绘制
            continue;
        }
        //柱形的开始位置
        CGFloat startX = MARGIN_LEFT + (index ) * MARGIN_BETWEEN_X_POINT - BAR_WIDTH/2;
        CGFloat startY = self.frame.size.height - (MARGIN_TOP + [item.coordinateYValue integerValue]*(self.dashedSpace/self.yNumberSpace));
        CGRect itemRect = CGRectMake(startX, startY, BAR_WIDTH, [item.coordinateYValue integerValue]*(self.dashedSpace/self.yNumberSpace));
        [self drawBarWithRect:itemRect];
        
        /*  使用CoreGraphics直接绘制
         CGContextMoveToPoint(currentCtx, startX, startY);
         CGContextAddRect(currentCtx, itemRect);
         CGContextSetFillColorWithColor(currentCtx, self.barColor.CGColor);
         CGContextFillPath(currentCtx);
         */
    }
    CGContextStrokePath(currentCtx);
}

/**
 *  @author li_yong
 *
 *  绘制柱形
 *
 *  @param itemRect 柱形的大小和位置
 */
- (void)drawBarWithRect:(CGRect)itemRect
{
    CAShapeLayer *barLayer = [CAShapeLayer layer];
    //设置图形线条的宽度
    barLayer.lineWidth = 1;
    barLayer.lineCap = kCALineCapButt;
    //设置图形线条的颜色
    barLayer.strokeColor = self.barColor.CGColor;
    //设置图形的填充色
    barLayer.fillColor = self.barColor.CGColor;
    
    CGMutablePathRef barPath = CGPathCreateMutable();
    CGPathMoveToPoint(barPath, nil, itemRect.origin.x, itemRect.origin.y);
    CGPathAddRect(barPath, nil, itemRect);
    barLayer.path = barPath;
    CGMutablePathRef initBarPath = CGPathCreateMutable();
    CGPathMoveToPoint(initBarPath, nil, itemRect.origin.x, self.frame.size.height - MARGIN_TOP);
    CGPathAddRect(initBarPath, nil, CGRectMake(itemRect.origin.x, self.frame.size.height - MARGIN_TOP, itemRect.size.width, 0));
    
    if (self.isAnimation)
    {
        CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
        pathAnimation.duration = ANIMATION_DURINGo;
        pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        pathAnimation.fromValue = (__bridge id)initBarPath;
        pathAnimation.toValue = (__bridge id)barPath;
        //是否翻转绘制
        pathAnimation.autoreverses = NO;
        pathAnimation.fillMode = kCAFillModeForwards;
        [barLayer addAnimation:pathAnimation forKey:@"path"];
    }
    
    [self.layer addSublayer:barLayer];
    CGPathRelease(barPath);
    CGPathRelease(initBarPath);
}

@end

#pragma PieChartView

@interface PieChartView()

//是否动态绘制
@property (assign, nonatomic) BOOL isAnimation;
//数据源
@property (strong, nonatomic) NSMutableArray *dataSource;
//百分比数组
@property (strong, nonatomic) NSMutableArray *percentArray;
//角度值数组
@property (strong, nonatomic) NSMutableArray *angleArray;

@end

@implementation PieChartView

/**
 *  @author li_yong
 *
 *  构造函数
 *
 *  @param dataSource 数据源
 *
 *  @return
 */
- (id)initWithDataSource:(NSMutableArray *)dataSource withAimation:(BOOL)isAnimation
{
    self = [super init];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        self.isAnimation = isAnimation;
        [self buildDataSourceWith:dataSource];
    }
    return self;
}

- (void)buildDataSourceWith:(NSMutableArray *)dataSource
{
    self.dataSource = [NSMutableArray arrayWithArray:dataSource];
    
    //根据传进来的数据计算比例数据
    __block CGFloat totalData = 0.0;
    __weak PieChartView *weakSelf = self;
    self.percentArray = [NSMutableArray arrayWithCapacity:0];
    self.angleArray = [NSMutableArray arrayWithCapacity:0];
    
    [self.dataSource enumerateObjectsUsingBlock:^(CoordinateItem *obj, NSUInteger idx, BOOL *stop) {
        //统计总值
        totalData = totalData + [obj.coordinateYValue floatValue];
    }];
    
    [self.dataSource enumerateObjectsUsingBlock:^(CoordinateItem *obj, NSUInteger idx, BOOL *stop) {
        //统计百分比
        CGFloat percent = [obj.coordinateYValue floatValue]/totalData;
        NSNumber *percentNumber = [NSNumber numberWithFloat:percent];
        [weakSelf.percentArray addObject:percentNumber];
        //统计角度值
        CGFloat angle = Angle(percent);
        NSNumber *angleNumber = [NSNumber numberWithFloat:angle];
        [weakSelf.angleArray addObject:angleNumber];
    }];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    //设置饼状图的半径(PIE_RADIUS是最大的半径)
    if((self.pieRadius == 0)||
       (self.pieRadius > PIE_RADIUS))
    {
        self.pieRadius = PIE_RADIUS;
    }
    
    __weak PieChartView *weakSelf = self;
    __block CGFloat endAngle = 0.0;
    __block CGFloat startAngle = 0.0;
    [self.angleArray enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL *stop) {
        //绘制的弧度大小
        CGFloat duringAngle = [obj floatValue];
        //计算开始弧度
        startAngle = endAngle;
        //计算结束弧度
        endAngle = startAngle + duringAngle;
        //绘制扇形
        [weakSelf drawPinWithStartAngle:startAngle
                           withEndAngle:endAngle
                              withIndex:idx];
    }];
}

/**
 *  @author li_yong
 *
 *  绘制扇形
 *
 *  @param startAngle 扇形的开始角度
 *  @param endAngle   扇形的结束角度
 *  @param idx        数据项的序号
 */
- (void)drawPinWithStartAngle:(CGFloat)startAngle
                 withEndAngle:(CGFloat)endAngle
                    withIndex:(NSUInteger)idx
{
    CAShapeLayer *pieLayer = [CAShapeLayer layer];
    //这里设置填充线的宽度，这个参数很重要
    pieLayer.lineWidth = self.pieRadius*2;
    //设置线端点样式，这个也是非常重要的一个参数
    pieLayer.lineCap = kCALineCapButt;
    //设置绘制的颜色
    CoordinateItem *item = [self.dataSource objectAtIndex:idx];
    pieLayer.strokeColor = item.itemColor.CGColor;
    pieLayer.fillColor = nil;
    
    //绘制图形
    CGMutablePathRef piePath  = CGPathCreateMutable();
    CGPathAddArc(piePath, &CGAffineTransformIdentity, self.center.x, self.center.y, self.pieRadius, startAngle, endAngle, NO);
    pieLayer.path = piePath;
    
    //是否动态绘制
    if (self.isAnimation)
    {
        CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        //设置绘制动画持续的时间
        pathAnimation.duration = ANIMATION_DURINGo;
        pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
        //是否翻转绘制
        pathAnimation.autoreverses = NO;
        pathAnimation.fillMode = kCAFillModeForwards;
        [pieLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    }
    //表示绘制到百分比多少就停止，这个我们用1表示完全绘制
    //    pieLayer.strokeEnd = 1.0;
    
    //该属性表示如果图形绘制超过的容器的范围是否被裁掉，这里我们设置为YES ，表示要裁掉超出范围的绘制
    //    self.clipsToBounds = NO;
    [self.layer addSublayer:pieLayer];
    //    CGPathRelease(piePath);
}

@end

